package com.springboot.framework.service.impl;

import com.springboot.framework.dao.entity.Coupons;
import com.springboot.framework.dao.mapper.CouponsMapper;
import com.springboot.framework.enums.CouponsEnum;
import com.springboot.framework.enums.Errors;
import com.springboot.framework.enums.StatusEnum;
import com.springboot.framework.exception.BusinessException;
import com.springboot.framework.model.CouponsModel;
import com.springboot.framework.service.CouponsService;
import com.springboot.framework.utils.MoneyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author SWF
 * @date 2019/6/20 9:51
 **/
@Service
@Slf4j
public class CouponsServiceImpl implements CouponsService {

    @Resource
    private CouponsMapper couponsMapper;
    /**
     * 查看未删除的优惠券信息
     * @param couponsId
     * @return
     */
    @Override
    public CouponsModel get(Integer couponsId) {
        Example example = new Example(Coupons.class);
        example.and().andEqualTo("couponsId", couponsId)
                .andNotEqualTo("status", StatusEnum.DELETE.getCode());
        Coupons coupons = couponsMapper.selectOneByExample(example);
        return convertCouponsModelFromCoupons(coupons);
    }

    /**
     * 查看未删除的优惠券列表
     * @return
     */
    @Override
    public List<CouponsModel> list() {
        Example example = new Example(Coupons.class);
        example.and().andNotEqualTo("status", StatusEnum.DELETE.getCode());
        example.orderBy("createDate").desc();
        List<Coupons> couponsList = couponsMapper.selectByExample(example);
        return convertCouponsModelFromCoupons(couponsList);
    }

    /**
     * 添加优惠券
     *
     * @param couponsModel
     * @return
     */
    @Override
    public CouponsModel insert(CouponsModel couponsModel) {
        Coupons coupons = new Coupons();
        BeanUtils.copyProperties(couponsModel,coupons);
        coupons.setCouponsAmount(MoneyUtil.moneyYuanToFen(couponsModel.getCouponsAmount()));
        coupons.setStatus((byte) 1);
        checkTypeAndValue(coupons);
        int resultCount = couponsMapper.insertSelective(coupons);
        if(resultCount == 0){
            throw new BusinessException("添加失败");
        }
        return convertCouponsModelFromCoupons(coupons);
    }

    @Override
    public CouponsModel update(CouponsModel couponsModel) {
        if(couponsModel.getCouponsId() == null){
            log.warn("【优惠券更新】优惠券id不能为空");
            throw new BusinessException("优惠券id不能为空");
        }
        Coupons coupons = new Coupons();
        BeanUtils.copyProperties(couponsModel,coupons);
        if(couponsModel.getCouponsAmount() != null){
            coupons.setCouponsAmount(MoneyUtil.moneyYuanToFen(couponsModel.getCouponsAmount()));
        }
        checkTypeAndValue(coupons);
        int resultCount = couponsMapper.updateByPrimaryKeySelective(coupons);
        if(resultCount == 0){
            throw new BusinessException("修改失败");
        }
        return convertCouponsModelFromCoupons(coupons);
    }

    /**
     * 删除优惠券发券信息
     *
     * @param couponsId
     */
    @Override
    public void delete(Integer couponsId) {
        Coupons coupons = new Coupons();
        coupons.setCouponsId(couponsId);
        coupons.setStatus(StatusEnum.DELETE.getCode());
        int resultCount = couponsMapper.updateByPrimaryKeySelective(coupons);
        if(resultCount == 0){
            throw new BusinessException("删除失败");
        }
    }

    @Override
    public void decreaseStock(Integer couponsId) {
        try {
            couponsMapper.decreaseStock(couponsId);
        }catch (Exception e){
            // 修改优惠券状态为无库存
            Coupons coupons = new Coupons();
            coupons.setCouponsId(couponsId);
            coupons.setStatus(new Byte("2"));
            couponsMapper.updateByPrimaryKeySelective(coupons);
            throw new BusinessException(Errors.COUPONS_STOCK_ERROR);
        }
    }

    private void checkTypeAndValue(Coupons coupons){
        if(CouponsEnum.TYPE_FIXED_DATE.getCode().equals(coupons.getType())){
            if(coupons.getEffectiveDate() == null | coupons.getExpiryDate() == null){
                throw new BusinessException("参数错误:固定时间");
            }
            coupons.setEffectiveDuration(null);
        }else {
            if(coupons.getEffectiveDuration() == null){
                throw new BusinessException("参数错误:固定时长");
            }
            coupons.setEffectiveDate(null);
            coupons.setExpiryDate(null);
        }
    }

    private CouponsModel convertCouponsModelFromCoupons(Coupons coupons){
        if(coupons == null){
            return null;
        }
        CouponsModel couponsModel = new CouponsModel();
        BeanUtils.copyProperties(coupons,couponsModel);
        // 数值类型转换
        couponsModel.setCouponsAmount(MoneyUtil.moneyFenToYuan(coupons.getCouponsAmount()));
        return couponsModel;
    }

    private List<CouponsModel> convertCouponsModelFromCoupons(List<Coupons> couponsList){
        if(couponsList == null){
            return null;
        }
        List<CouponsModel> couponsModelList = couponsList.stream()
                .map(e->convertCouponsModelFromCoupons(e))
                .collect(Collectors.toList());
        return couponsModelList;
    }
}
